package com.westcom.vulb.activity;

import java.util.ArrayList;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.westcom.vulb.bean.Session;
import com.westcom.vulb.logic.SessionManager;
import com.westcom.vulb.logic.account;
import com.westcom.vulb.logic.share;
import com.westcom.vulb.logic.sheet;
import com.westcom.vulb.protocal.http.Response;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Parcelable;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.util.DisplayMetrics;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.TranslateAnimation;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;

public class AddShareMemberActivity extends BasicActivity
{
	//view pager
	private ViewPager mPager;
	private int currIndex = 0;
	private List<View> Views; 
	private ImageView cursor,iv_back;
	private Button btn_invited,btn_fb,btn_invite_by_id;
	private TextView tv_done;
	private int bmpW;
	//list view
	List<userNode> invited_member_list = new ArrayList<userNode>();
	ListView invited_list = null;
	ListView fb_list = null;
	
	List<userNode> fb_member_list = new ArrayList<userNode>();
	listAdapter invited_adapter = null;
	listAdapter fb_adapter = null;
	
	List<userNode> invited_show_list = new ArrayList<userNode>();
	///
	
	int mCurrentSheetId = -1;
	private ProgressDialog mLoadingDialog;
	private SessionManager sm;
	private List<userNode> Sheetmemberlist = new ArrayList<userNode>();
	
	///
	OnClickListener l = null;
	
	
	@Override
	protected void onCreate(Bundle savedInstanceState) 
	{
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_add_share_member);
		mCurrentSheetId = this.getIntent().getIntExtra("sheetId", -1);
		init();
		GetInvitedShowMemeberListTask getInvitedListtask = new GetInvitedShowMemeberListTask();
		mLoadingDialog = ProgressDialog.show(this, this.getResources().getString(R.string.wait),this.getResources().getString(R.string.processing));
		getInvitedListtask.execute("");
	}
	private void init()
	{
		sm = SessionManager.getInstance();
		InitViews();
		InitViewPager();
		InitCursor();
	}
	
	private void InitCursor() {
		cursor = (ImageView) findViewById(R.id.cursor);
		Bitmap cu = BitmapFactory.decodeResource(getResources(), R.drawable.img_cursor);
		DisplayMetrics dm = new DisplayMetrics();
		getWindowManager().getDefaultDisplay().getMetrics(dm);
		int screenW = dm.widthPixels;
		bmpW = screenW/2;
		Bitmap mBitmap = Bitmap.createScaledBitmap(cu,bmpW, cu.getHeight(), true);
		cursor.setImageBitmap(mBitmap);
	}
	
	private void InitViewPager() 
	{
		mPager = (ViewPager) findViewById(R.id.vPager);

		Views = new ArrayList<View>();
		Views.add(invited_list);
		Views.add(fb_list);
		mPager.setAdapter(new MyPagerAdapter(Views));
		mPager.setCurrentItem(0);
		mPager.setOnPageChangeListener(new MyOnPageChangeListener());
		
		iv_back = (ImageView)findViewById(R.id.iv_add_share_member_header_left);
		tv_done = (TextView)findViewById(R.id.tv_add_share_member_header_right);
		btn_invited = (Button)findViewById(R.id.btn_invited);
		btn_fb = (Button)findViewById(R.id.btn_fb);
		btn_invite_by_id = (Button)findViewById(R.id.btn_invite_by_mail);
		l = new OnClickListener()
		{
			@Override
			public void onClick(View v) 
			{
				// TODO Auto-generated method stub
				switch(v.getId())
				{
					case R.id.btn_invited:
					{
						mPager.setCurrentItem(0);
					}break;
					case R.id.btn_fb:
					{
						mPager.setCurrentItem(1);
					}break;
					case R.id.iv_add_share_member_header_left:
					{
						finish();
					}break;
					case R.id.tv_add_share_member_header_right:
					{
						Integer[] ids = getClickedItem();
						if(ids.length>0)
						{
							mLoadingDialog = ProgressDialog.show(AddShareMemberActivity.this,getResources().getString(R.string.wait),getResources().getString(R.string.processing));
							InviteUserByIdsTask task = new InviteUserByIdsTask();
							task.execute(ids);
						}
					}break;
					case R.id.btn_invite_by_mail:
					{
						Intent intent = new Intent();
		    	        intent.putExtra("sheetId",mCurrentSheetId);    
		    	        intent.setClass(AddShareMemberActivity.this, InputAddShareMemberMailActivity.class);
		    	        AddShareMemberActivity.this.startActivity(intent);	
					}break;
					default:{}break;
				}
		}};
		iv_back.setOnClickListener(l);
		tv_done.setOnClickListener(l);
		btn_invited.setOnClickListener(l);
		btn_fb.setOnClickListener(l);
		btn_invite_by_id.setOnClickListener(l);
	}
	
	private void InitViews()
	{
		invited_list = new ListView(this);
		invited_adapter = new listAdapter(this,invited_show_list);
		invited_list.setAdapter(invited_adapter);
		invited_list.setOnItemClickListener
		(
			new OnItemClickListener()
			{
				@Override
				public void onItemClick(AdapterView<?> arg0, View arg1, int position,long id) 
				{
					// TODO Auto-generated method stub
					invited_show_list.get(position).mIsClicked = !invited_show_list.get(position).mIsClicked;
					invited_adapter.notifyDataSetChanged();
				}
			}
		);
		
		fb_list = new ListView(this);
		fb_adapter = new listAdapter(this,fb_member_list);
		fb_list.setAdapter(fb_adapter);
		fb_list.setOnItemClickListener
		(
			new OnItemClickListener()
			{
				@Override
				public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,long arg3) 
				{
					// TODO Auto-generated method stub
				}
			}
		);
	}
	public class MyOnPageChangeListener implements OnPageChangeListener {
		@Override
		public void onPageSelected(int arg0) {
			Animation animation = null;
			switch (arg0) {
			case 0:
				if (currIndex == 1) 
				{
					animation = new TranslateAnimation(bmpW, 0, 0, 0);
				}
				break;
			case 1:
				if (currIndex == 0) {
					animation = new TranslateAnimation(0, bmpW, 0, 0);
				}
				break;
			}
			currIndex = arg0;
			animation.setFillAfter(true);
			animation.setDuration(300);
			cursor.startAnimation(animation);
		}

		@Override
		public void onPageScrolled(int arg0, float arg1, int arg2) {
		}

		@Override
		public void onPageScrollStateChanged(int arg0) {
		}
	}
	public class MyPagerAdapter extends PagerAdapter {
		public List<View> mListViews;

		public MyPagerAdapter(List<View> mListViews) {
			this.mListViews = mListViews;
		}

		@Override
		public void destroyItem(View arg0, int arg1, Object arg2) {
			((ViewPager) arg0).removeView(mListViews.get(arg1));
		}

		@Override
		public void finishUpdate(View arg0) {
		}

		@Override
		public int getCount() {
			return mListViews.size();
		}

		@Override
		public Object instantiateItem(View arg0, int arg1) {
			((ViewPager) arg0).addView(mListViews.get(arg1), 0);
			return mListViews.get(arg1);
		}

		@Override
		public boolean isViewFromObject(View arg0, Object arg1) {
			return arg0 == (arg1);
		}

		@Override
		public void restoreState(Parcelable arg0, ClassLoader arg1) {
		}

		@Override
		public Parcelable saveState() {
			return null;
		}

		@Override
		public void startUpdate(View arg0) {
		}
	}
	
	public class listAdapter extends BaseAdapter {
		
		private Context context;
		private List<userNode> info = null;
		public listAdapter(Context context,List<userNode> data) 
		{
			this.context = context;
			info = data;
		}
		@Override
		public int getCount() 
		{
			// TODO Auto-generated method stub
			return info == null? 0:info.size();
		}

		@Override
		public Object getItem(int arg0) 
		{
			// TODO Auto-generated method stub
			return null;
		}

		@Override
		public long getItemId(int arg0) 
		{
			// TODO Auto-generated method stub
			return 0;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) 
		{
			// TODO Auto-generated method stub
			View v;				
			if (convertView == null) 
			{
	            v = View.inflate(context, R.layout.item_add_share_member, null);
	        }
			else 
			{
				v = convertView;
			}
			userNode u = info.get(position);
			if(null == u)
			{
				return v;
			}
			ImageView profile_img = (ImageView)v.findViewById(R.id.iv_add_share_member_profile_img);
			TextView account = (TextView)v.findViewById(R.id.tv_add_share_member_account);
			ImageView check_img = (ImageView)v.findViewById(R.id.iv_add_share_member_check);
			if(u.mImg != null)
			{
				profile_img.setImageBitmap(u.mImg);
			}
			account.setText(u.mName);
			if(u.mIsClicked)
			{
				check_img.setVisibility(View.VISIBLE);
			}else
			{
				check_img.setVisibility(View.GONE);
			}
			int tag = position;
    		v.setTag(tag);
			return v;
		}
	}
	private String InviteUserByIds(Integer[] p)
	{
		int[] ids = new int[p.length];
		for(int i = 0;i<p.length;i++)
		{
			ids[i] = p[i].intValue();
		}
		Response res = null;
    	share sh = share.getInstanse();
    	res = sh.InviteWithId(sm.getCurrSessionId(), mCurrentSheetId, ids);
    	if(res.errno == Response.SUCCESS)
    	{
    		return null;
    	}else
    	{
    		return res.errmsg;
    	}
	}
	private class InviteUserByIdsTask extends AsyncTask<Integer, Integer, String> {
        @Override
        protected String doInBackground(Integer... params) 
        {
            return InviteUserByIds(params);
        }
        @Override
        protected void onCancelled() {
            super.onCancelled();
            if(mLoadingDialog.isShowing())
        	{
        		mLoadingDialog.hide();
        	}
        }
        @Override  
        protected void onPostExecute(String result) 
        {  
        	super.onPostExecute(result);
        	if(result != null)
        	{
        		launchToast(result);
        	}else
        	{
        		buildShowList();
        	}
        	if(mLoadingDialog.isShowing())
        	{
        		mLoadingDialog.hide();
        	}
        	invited_adapter.notifyDataSetChanged();
        }
	}
	
	private class GetInvitedShowMemeberListTask extends AsyncTask<String, Integer, String> {
        @Override
        protected String doInBackground(String... params) 
        {
            return getInvitedShowList();
        }
        @Override
        protected void onCancelled() {
            super.onCancelled();
            if(mLoadingDialog.isShowing())
        	{
        		mLoadingDialog.hide();
        	}
        }
        @Override  
        protected void onPostExecute(String result) 
        {  
        	super.onPostExecute(result);
        	if(result != null)
        	{
        		launchToast(result);
        	}
        	if(mLoadingDialog.isShowing())
        	{
        		mLoadingDialog.hide();
        	}
        	invited_adapter.notifyDataSetChanged();
        }
	}
	
	private String getInvitedShowList()
	{
		String res = null;
		res = getMemberList();
		if(res != null)
		{
			return res;
		}
		res = getInvitedList();
		if(res != null)
		{
			return res;
		}
		buildShowList();
		return null;
	}
	
	private String getMemberList()
	{
		Response res = null;
    	sheet sh = sheet.getInstanse();
    	res = sh.GetSheetMemberList(sm.getCurrSessionId(),mCurrentSheetId);
    	JSONArray users = (JSONArray)res.data.get("members");
    	Session s = sm.getCurrentSession();
    	userNode u = null;
    	Sheetmemberlist.clear();
    	for(int i = 0;i<users.length();i++)
    	{
    		//"userName":"viking","userId":76
    		try 
    		{
				JSONObject o = (JSONObject) users.get(i);
				u = new userNode(o.getString("userName"),o.getInt("userId"));
    			u.mStatus = o.getString("memberStatus");
    			u.mOwnFlg = o.getString("ownFlg");
    			Sheetmemberlist.add(u);
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
    	}
    	if(res.errno == Response.SUCCESS)
    	{
    		return null;
    	}else
    	{
    		return res.errmsg;
    	}
	}
	private String getInvitedList()
	{
		Response res = null;
    	share sh = share.getInstanse();
    	res = sh.getInvitedList(sm.getCurrSessionId());
    	JSONArray users = (JSONArray)res.data.get("users");
    	Session s = sm.getCurrentSession();
    	userNode u = null;
    	invited_member_list.clear();
    	for(int i = 0;i<users.length();i++)
    	{
    		//"userName":"viking","userId":76
    		try 
    		{
				JSONObject o = (JSONObject) users.get(i);
				u = new userNode(o.getString("userName"),o.getInt("userId"));
				res = s.getProfileImage(true,u.mId);
				String bitmap_str = (String) res.data.get("personImg");
    			u.mImg = account.Base64Str2Bitmap(bitmap_str);
    			invited_member_list.add(u);
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
    	}
    	if(res.errno == Response.SUCCESS)
    	{
    		return null;
    	}else
    	{
    		return res.errmsg;
    	}
	}
	private void buildShowList()
	{
		boolean flag = false;
		invited_show_list.clear();
		for(userNode u1:invited_member_list)
		{
			for(userNode u2:Sheetmemberlist)
			{
				if(u1.mId == u2.mId && u2.mStatus.equals("0"))
				{
					flag = true;
					break;
				}
			}
			if(flag)
			{
				flag = false;
				continue;
			}else
			{
				invited_show_list.add(u1);
			}
			u1.mIsClicked = false;
		}
	}
	private Integer[] getClickedItem()
	{
		List<Integer> ids = new ArrayList<Integer>();
		for(userNode u:invited_show_list)
		{
			if(u.mIsClicked)
			{
				ids.add(u.mId);
			}
		}
		return ids.toArray(new Integer[ids.size()]);
	}
}
